/*
 * @Description:
 * @Author: fhw
 * @Date: 2023-02-08 10:05:40
 */
import { Injectable, UseFilters } from '@nestjs/common';
import { Between, Like, Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { UserEntity } from './entities/user.entity';
import { JwtService } from '@nestjs/jwt';
import { HttpExceptionFilter } from 'src/common/http-exception.filter';
import { getPagination, throwHttp } from 'src/utlis';
import { GetUserPage, GetUserInfoDto, UpdatePassWordDto, UpdateUserInfoDto } from './dto/user.dto';
import { compareSync, hashSync } from 'bcryptjs';
import { isNil } from 'ramda';
import { Status } from 'src/dictionaries/index.enum';
@Injectable()
export class UserService {
  constructor(
    @InjectRepository(UserEntity)
    private readonly userRepository: Repository<UserEntity>,
  ) { }

  async getUserPage(params: GetUserPage) {
    try {
      const {
        createTimeStart,
        createTimeEnd,
        updateTimeEnd,
        updateTimeStart,
        username,
        status,
        email,
        mobile,
        gender,
        coupleId,
        id,
      } = params;
      const { pageSize, pageNum } = getPagination({
        pageSize: params.pageSize,
        pageNum: params.pageNum,
      });
      const where: GetUserPage = {
        username: Like(`%${username || ''}%`),
        coupleId,
        status,
        email,
        mobile,
        gender,
        id,
      };
      // 创建时间筛选
      if (!isNil(createTimeStart) && !isNil(createTimeEnd)) {
        where.createDate = Between(createTimeStart, createTimeEnd);
      }
      // 更新时间筛选
      if (!isNil(updateTimeStart) && !isNil(updateTimeEnd)) {
        where.updateDate = Between(updateTimeStart, updateTimeEnd);
      }
      const [data, total] = await this.userRepository.findAndCount({
        where,
        cache: true,
        skip: pageNum * pageSize,
        take: pageSize,
        order: { createDate: 'DESC' },
        relations: []
      });
      return {
        data,
        total,
        pageSize,
        pageNum: pageNum + 1,
      };
    } catch (error) {
      throwHttp(error.message);
    }
  }

  /** 修改密码 */
  @UseFilters(new HttpExceptionFilter())
  async updatePassWord(params: UpdatePassWordDto, userId: number) {
    try {
      const { old_password, new_password } = params;
      const userInfo = await this.userRepository.findOne({
        where: { id: userId },
        select: ['password'],
      });
      if (isNil(userInfo)) {
        throwHttp('用户不存在');
        return;
      }
      if (!compareSync(old_password, userInfo.password)) {
        throwHttp('登录密码不正确');
        return
      }
      if (compareSync(new_password, userInfo.password)) {
        throwHttp('新密码不能与旧密码一致');
        return
      }
      const { affected } = await this.userRepository
        .createQueryBuilder()
        .update(UserEntity)
        .set({
          password: await hashSync(new_password),
        })
        .where('id = :id', { id: userId })
        .execute();
      if (affected) {
        return '密码修改成功';
      }
      throwHttp('密码修改失败');
    } catch (error) {
      throwHttp(error.message);
    }
  }

  /** 获取用户信息 */
  @UseFilters(new HttpExceptionFilter())
  async getUserInfo(id: number, relations = []): Promise<UserEntity> {
    try {
      if (!id) {
        throwHttp('参数为空');
      }
      const data = await this.userRepository.findOne({
        where: { id, status: Status.ENABLED },
        relations
      });
      if (isNil(data)) {
        throwHttp('用户不存在');
        return;
      }
      return data;
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 修改用户信息 */
  @UseFilters(new HttpExceptionFilter())
  async updateUserInfo(body: UpdateUserInfoDto, userId: number) {
    try {
      const { username, QQ, mobile, avatar, description, gender } = body
      const userInfo = await this.userRepository.findOne({
        where: { id: userId },
        select: ['id'],
      });
      if (isNil(userInfo)) {
        throwHttp('用户不存在');
        return;
      }
      const { affected } = await this.userRepository
        .createQueryBuilder()
        .update(UserEntity)
        .set({
          username, QQ, mobile, avatar, description, gender: `${gender}`
        })
        .where('id = :id', { id: userId })
        .execute();
      if (affected) {
        return '用户信息修改成功';
      }
      throwHttp('用户信息修改失败');
    } catch (error) {
      throwHttp(error.message);
    }
  }
}
